package net.ankao.job.job;

import lombok.extern.slf4j.Slf4j;
import net.ankao.job.common.HeartbeatNamingManager;
import net.ankao.job.core.rpc.IAkJobClientService;
import net.ankao.job.entity.AkApplicationClient;
import net.ankao.job.service.IAkApplicationClientService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.annotation.Resource;
import java.rmi.RemoteException;
import java.util.List;

/**
 * @author LILU
 * @date 2024-11-28 9:22
 */
@Slf4j
public class HeartbeatJob implements Job {

    @Resource
    private IAkApplicationClientService akApplicationClientService;

    @Resource
    private HeartbeatNamingManager heartbeatNamingManager;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        List<AkApplicationClient> list = akApplicationClientService.list();
        list.parallelStream().forEach(akApplicationClient -> {
            IAkJobClientService naming = heartbeatNamingManager.getNaming(akApplicationClient.getId());
            if (naming == null) {
                akApplicationClientService.downUp(akApplicationClient.getId());
                return;
            }
            try {
                naming.heartbeat();
                akApplicationClientService.heartbeat(akApplicationClient.getId());
            } catch (RemoteException e) {
                // 下线了
                akApplicationClientService.downUp(akApplicationClient.getId());
            }
        });
    }
}
